<template>
  <div class="min-h-screen bg-gray-50 pt-16">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="bg-white rounded-lg shadow-lg p-6">
        <h1 class="text-3xl font-bold text-gray-900 mb-8">教案生成器</h1>

        <!-- 步骤指示器 -->
        <div class="mb-8">
          <div class="flex items-center justify-between">
            <div v-for="(step, index) in steps" :key="index" class="flex items-center cursor-pointer"
              :class="{ 'flex-1': index < steps.length - 1 }" @click="goToStep(index + 1)">
              <div
                class="flex items-center justify-center w-8 h-8 rounded-full text-sm font-medium transition-colors hover:bg-blue-500 hover:text-white"
                :class="currentStep >= index + 1 ? 'bg-blue-600 text-white' : 'bg-gray-300 text-gray-600'">
                {{ index + 1 }}
              </div>
              <span class="ml-2 text-sm font-medium transition-colors"
                :class="currentStep >= index + 1 ? 'text-blue-600' : 'text-gray-500'">
                {{ step }}
              </span>
              <div v-if="index < steps.length - 1" class="flex-1 h-0.5 bg-gray-300 mx-4"
                :class="currentStep > index + 1 ? 'bg-blue-600' : 'bg-gray-300'"></div>
            </div>
          </div>
        </div>

        <!-- 步骤1: 文档转换 -->
        <div v-if="currentStep === 1" class="space-y-6">
          <h2 class="text-xl font-semibold text-gray-900">步骤1: 文档转换</h2>

          <!-- DOC转MD -->
          <div class="border rounded-lg p-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">DOC文件转换为Markdown</h3>
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">选择DOC文件</label>
                <input type="file" @change="handleDocFileSelect" accept=".doc,.docx"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
              </div>
              <div v-if="selectedDocFile">
                <p class="text-sm text-gray-600 mb-2">已选择文件: {{ selectedDocFile.name }}</p>
                <button @click="convertDocToMd" :disabled="!selectedDocFile || isConverting"
                  class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400">
                  <i class="fas fa-sync-alt mr-2" :class="{ 'fa-spin': isConverting }"></i>
                  {{ isConverting ? '转换中...' : '开始转换' }}
                </button>
              </div>
            </div>

            <!-- 转换结果 -->
            <div v-if="conversionResults.length > 0" class="mt-4">
              <h4 class="text-sm font-medium text-gray-700 mb-2">转换结果:</h4>
              <div class="bg-gray-50 rounded-md p-3 max-h-40 overflow-y-auto">
                <div v-for="result in conversionResults" :key="result.file" class="text-sm">
                  <span :class="result.success ? 'text-green-600' : 'text-red-600'">
                    {{ result.success ? '✓' : '✗' }} {{ result.file }}
                  </span>
                  <span v-if="!result.success" class="text-red-500 ml-2">{{ result.error }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- PPTX转MD -->
          <div class="border rounded-lg p-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">PPTX文件转换为Markdown</h3>
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">选择PPTX文件</label>
                <input type="file" @change="handlePptxFileSelect" accept=".pptx"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
              </div>
              <div v-if="selectedPptxFile">
                <p class="text-sm text-gray-600 mb-2">已选择文件: {{ selectedPptxFile.name }}</p>
                <div class="space-y-2">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">输出文件名（可选）</label>
                    <input v-model="pptxOutputName" type="text" placeholder="默认为 ppt.md"
                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">图片目录（可选）</label>
                    <input v-model="pptxImageDir" type="text" placeholder="默认为 img"
                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                  </div>
                  <div class="flex items-center space-x-4">
                    <label class="flex items-center">
                      <input type="checkbox" v-model="pptxDisableImage" class="mr-2">
                      <span class="text-sm text-gray-700">禁用图片提取</span>
                    </label>
                    <label class="flex items-center">
                      <input type="checkbox" v-model="pptxEnableSlides" class="mr-2">
                      <span class="text-sm text-gray-700">启用幻灯片分隔符</span>
                    </label>
                  </div>
                  <button @click="convertPptxToMd" :disabled="!selectedPptxFile || isPptxConverting"
                    class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:bg-gray-400">
                    <i class="fas fa-sync-alt mr-2" :class="{ 'fa-spin': isPptxConverting }"></i>
                    {{ isPptxConverting ? 'PPTX转换中...' : '开始转换PPTX' }}
                  </button>
                </div>
              </div>
            </div>

            <!-- PPTX转换结果 -->
            <div v-if="pptxConversionResults.length > 0" class="mt-4">
              <h4 class="text-sm font-medium text-gray-700 mb-2">PPTX转换结果:</h4>
              <div class="bg-gray-50 rounded-md p-3 max-h-40 overflow-y-auto">
                <div v-for="result in pptxConversionResults" :key="result.file" class="text-sm">
                  <span :class="result.success ? 'text-green-600' : 'text-red-600'">
                    {{ result.success ? '✓' : '✗' }} {{ result.file }}
                  </span>
                  <span v-if="!result.success" class="text-red-500 ml-2">{{ result.error }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 下一步按钮 -->
          <div class="flex justify-end">
            <button @click="nextStep" class="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
              下一步
            </button>
          </div>
        </div>

        <!-- 步骤2: 选择文件和模板 -->
        <div v-if="currentStep === 2" class="space-y-6">
          <h2 class="text-xl font-semibold text-gray-900">步骤2: 选择文件和模板</h2>

          <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 选择MD文件 -->
            <div class="border rounded-lg p-4">
              <h3 class="text-lg font-medium text-gray-900 mb-4">选择Markdown文件</h3>
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">文件路径（支持多选）</label>
                  <input type="file" @change="handleMdFileSelect" accept=".md" multiple
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                  <p class="text-xs text-gray-500 mt-1">提示：按住Ctrl键可选择多个文件</p>
                </div>

                <!-- 已选择的文件列表 -->
                <div v-if="selectedMdFiles.length > 0" class="mt-4">
                  <h4 class="text-sm font-medium text-gray-700 mb-2">已选择的文件 ({{ selectedMdFiles.length }}个):</h4>
                  <div class="space-y-2 max-h-40 overflow-y-auto">
                    <div v-for="(mdFile, index) in selectedMdFiles" :key="index" 
                         class="flex items-center justify-between bg-blue-50 rounded-md p-2">
                      <div class="flex items-center space-x-2">
                        <i class="fas fa-file-alt text-blue-600"></i>
                        <span class="text-sm font-medium text-blue-800">{{ mdFile.name }}</span>
                        <span class="text-xs text-gray-500">({{ Math.round(mdFile.content.length / 1024) }}KB)</span>
                      </div>
                      <button @click="removeMdFile(index)" 
                              class="text-red-500 hover:text-red-700 text-sm">
                        <i class="fas fa-times"></i>
                      </button>
                    </div>
                  </div>
                </div>

                <!-- 文件预览 -->
                <div v-if="selectedMdFiles.length > 0" class="mt-4">
                  <h4 class="text-sm font-medium text-gray-700 mb-2">文件预览:</h4>
                  <div class="space-y-3">
                    <div v-for="(mdFile, index) in selectedMdFiles.slice(0, 3)" :key="index" 
                         class="bg-gray-50 rounded-md p-3">
                      <div class="flex items-center justify-between mb-2">
                        <span class="text-sm font-medium text-gray-700">{{ mdFile.name }}</span>
                        <button @click="toggleFilePreview(index)" 
                                class="text-xs text-blue-600 hover:text-blue-800">
                          {{ expandedPreviews.includes(index) ? '收起' : '展开' }}
                        </button>
                      </div>
                      <div class="max-h-32 overflow-y-auto">
                        <pre class="text-sm text-gray-800 whitespace-pre-wrap">{{ 
                          expandedPreviews.includes(index) 
                            ? mdFile.content 
                            : mdFile.content.substring(0, 200) + (mdFile.content.length > 200 ? '...' : '') 
                        }}</pre>
                      </div>
                    </div>
                    <div v-if="selectedMdFiles.length > 3" class="text-sm text-gray-500 text-center">
                      还有 {{ selectedMdFiles.length - 3 }} 个文件未显示预览
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 选择模板 -->
            <div class="border rounded-lg p-4">
              <h3 class="text-lg font-medium text-gray-900 mb-4">选择教案模板</h3>
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">模板文件</label>
                  <select v-model="selectedTemplate" @change="loadTemplate"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">请选择模板</option>
                    <option value="default">默认模板 (Template.md)</option>
                  </select>
                </div>

                <!-- 模板预览 -->
                <div v-if="templateContent" class="mt-4">
                  <h4 class="text-sm font-medium text-gray-700 mb-2">模板预览:</h4>
                  <div class="bg-gray-50 rounded-md p-3 max-h-60 overflow-y-auto">
                    <pre
                      class="text-sm text-gray-800 whitespace-pre-wrap">{{ templateContent.substring(0, 500) }}{{ templateContent.length > 500 ? '...' : '' }}</pre>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 对话生成模式 -->
          <div v-if="generationMode === 'chat'" class="space-y-6">
            <!-- AI模型配置 -->
            <div class="border rounded-lg p-4">
              <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900">AI模型配置</h3>
                <button @click="goToModelConfig"
                  class="px-3 py-1 text-sm bg-blue-100 text-blue-600 rounded-md hover:bg-blue-200 transition-colors">
                  <i class="fas fa-cog mr-1"></i>
                  模型配置
                </button>
              </div>
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">选择AI模型</label>
                  <select v-model="selectedLLM"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">请选择模型</option>
                    <option v-for="model in modelConfigStore.availableModels" :key="model.id" :value="model.id">
                      {{ model.name }}
                    </option>
                  </select>
                </div>
                <div v-if="selectedLLM">
                  <div class="flex items-center space-x-2">
                    <span v-if="modelConfigStore.getModelConfig(selectedLLM)?.apiKey"
                      class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                      <i class="fas fa-check-circle mr-1"></i>
                      模型已配置
                    </span>
                    <span v-else
                      class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                      <i class="fas fa-exclamation-circle mr-1"></i>
                      模型未配置
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 对话界面 -->
            <div class="border rounded-lg p-4">
              <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900">AI对话助手</h3>
                <div class="flex space-x-2">
                  <button @click="async () => { 
                    const result = await loadChatHistory();
                    if(result) {
                      ElMessage.success('对话历史已恢复');
                      scrollToBottom();
                    } else {
                      ElMessage.warning('没有保存的对话历史');
                    }
                  }"
                          class="px-2 py-1 text-xs bg-blue-100 text-blue-600 rounded hover:bg-blue-200">
                    <i class="fas fa-history mr-1"></i> 加载历史
                  </button>
                  <button @click="exportChatHistory" class="px-2 py-1 text-xs bg-green-100 text-green-600 rounded hover:bg-green-200">
                    <i class="fas fa-download mr-1"></i> 导出
                  </button>
                  <label class="px-2 py-1 text-xs bg-purple-100 text-purple-600 rounded hover:bg-purple-200 cursor-pointer">
                    <i class="fas fa-upload mr-1"></i> 导入
                    <input type="file" @change="importChatHistory" accept=".json" class="hidden">
                  </label>
                  <button @click="clearChat" class="px-2 py-1 text-xs bg-red-100 text-red-600 rounded hover:bg-red-200">
                    <i class="fas fa-trash mr-1"></i> 清空
                  </button>
                </div>
              </div>
              
              <!-- 聊天消息区域 -->
              <div class="bg-gray-50 rounded-lg p-4 h-96 overflow-y-auto mb-4" ref="chatContainer">
                <div v-if="chatMessages.length === 0" class="text-center text-gray-500 mt-20">
                  <i class="fas fa-comments text-4xl mb-4"></i>
                  <p>开始与AI助手对话，逐步完善您的教案</p>
                  <p class="text-sm mt-2">您可以上传文件、提出问题、要求修改等</p>
                </div>
                
                <div v-for="(message, index) in chatMessages" :key="index" class="mb-4">
                  <!-- 用户消息 -->
                  <div v-if="message.role === 'user'" class="flex justify-end">
                    <div class="max-w-3/4 bg-blue-600 text-white rounded-lg p-3">
                      <div v-if="message.files && message.files.length > 0" class="mb-2">
                        <div v-for="file in message.files" :key="file.name" 
                          class="flex items-center text-sm bg-blue-500 rounded p-2 mb-1">
                          <i class="fas fa-file mr-2"></i>
                          {{ file.name }}
                        </div>
                      </div>
                      <div class="whitespace-pre-wrap">{{ message.content }}</div>
                      <div class="text-xs text-blue-200 mt-1">{{ formatTime(message.timestamp) }}</div>
                    </div>
                  </div>
                  
                  <!-- AI消息 -->
                  <div v-else class="flex justify-start">
                    <div class="max-w-3/4 bg-white border rounded-lg p-3">
                      <div class="flex items-center mb-2">
                        <i class="fas fa-robot text-blue-600 mr-2"></i>
                        <span class="text-sm font-medium text-gray-700">AI助手</span>
                      </div>
                      <div class="prose max-w-none" v-html="marked(message.content)"></div>
                      <div class="text-xs text-gray-500 mt-1">{{ formatTime(message.timestamp) }}</div>
                    </div>
                  </div>
                </div>
                
                <!-- 正在输入指示器 -->
                <div v-if="isChatGenerating" class="flex justify-start">
                  <div class="bg-white border rounded-lg p-3">
                    <div class="flex items-center">
                      <i class="fas fa-robot text-blue-600 mr-2"></i>
                      <span class="text-sm font-medium text-gray-700">AI助手正在思考</span>
                      <div class="ml-2 flex space-x-1">
                        <div class="w-2 h-2 bg-blue-600 rounded-full animate-bounce"></div>
                        <div class="w-2 h-2 bg-blue-600 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                        <div class="w-2 h-2 bg-blue-600 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 输入区域 -->
              <div class="space-y-3">
                <!-- 文件上传区域 -->
                <div v-if="selectedChatFiles.length > 0" class="flex flex-wrap gap-2">
                  <div v-for="(file, index) in selectedChatFiles" :key="index" 
                    class="flex items-center bg-blue-100 text-blue-800 rounded-lg px-3 py-1 text-sm">
                    <i class="fas fa-file mr-2"></i>
                    {{ file.name }}
                    <button @click="removeChatFile(index)" class="ml-2 text-blue-600 hover:text-blue-800">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                </div>
                
                <!-- 输入框和按钮 -->
                <div class="flex space-x-2">
                  <div class="flex-1 relative">
                    <textarea v-model="chatInput" 
                      @keydown.enter.exact.prevent="sendChatMessage"
                      @keydown.enter.shift.exact="chatInput += '\n'"
                      rows="3" 
                      placeholder="输入您的问题或要求...(Enter发送，Shift+Enter换行)"
                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                      :disabled="isChatGenerating || !selectedLLM || !modelConfigStore.getModelConfig(selectedLLM)?.apiKey"></textarea>
                  </div>
                  <div class="flex flex-col space-y-2">
                    <input type="file" ref="chatFileInput" @change="handleChatFileSelect" 
                      accept=".md,.txt,.doc,.docx" multiple class="hidden">
                    <button @click="chatFileInput?.click()"
                      class="px-3 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors"
                      title="上传文件">
                      <i class="fas fa-paperclip"></i>
                    </button>
                    <button @click="sendChatMessage" 
                      :disabled="!chatInput.trim() || isChatGenerating || !selectedLLM || !modelConfigStore.getModelConfig(selectedLLM)?.apiKey"
                      class="px-3 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 transition-colors">
                      <i class="fas fa-paper-plane"></i>
                    </button>
                  </div>
                </div>
                
                <!-- 快捷操作按钮 -->
                <div class="flex flex-wrap gap-2">
                  <button @click="addQuickPrompt('请帮我分析这个文档的主要内容')"
                    class="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200">
                    分析文档
                  </button>
                  <button @click="addQuickPrompt('请根据模板生成教案大纲')"
                    class="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200">
                    生成大纲
                  </button>
                  <button @click="addQuickPrompt('请完善教案的教学目标部分')"
                    class="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200">
                    完善目标
                  </button>
                  <button @click="addQuickPrompt('请添加更多的教学活动和案例')"
                    class="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200">
                    添加活动
                  </button>
                  <button @click="clearChat"
                    class="px-3 py-1 text-sm bg-red-100 text-red-700 rounded-md hover:bg-red-200">
                    清空对话
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 导航按钮 -->
          <div class="flex justify-between">
            <button @click="prevStep" class="px-6 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700">
              上一步
            </button>
            <button @click="nextStep" :disabled="selectedMdFiles.length === 0 || !selectedTemplate"
              class="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400">
              下一步
            </button>
          </div>
        </div>

        <!-- 步骤3: LLM配置和生成 -->
        <div v-if="currentStep === 3" class="space-y-6">
          <h2 class="text-xl font-semibold text-gray-900">步骤3: AI生成教案</h2>

          <!-- 生成模式选择 -->
          <div class="border rounded-lg p-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">选择生成模式</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="border rounded-lg p-4 cursor-pointer transition-all"
                :class="generationMode === 'oneshot' ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-gray-400'"
                @click="generationMode = 'oneshot'">
                <div class="flex items-center mb-2">
                  <input type="radio" v-model="generationMode" value="oneshot" class="mr-2">
                  <h4 class="font-medium text-gray-900">一键生成模式</h4>
                </div>
                <p class="text-sm text-gray-600">基于选择的文件和模板，一次性生成完整教案</p>
                <div class="mt-2 text-xs text-gray-500">
                  <i class="fas fa-bolt mr-1"></i>快速、直接、适合标准化需求
                </div>
              </div>
              <div class="border rounded-lg p-4 cursor-pointer transition-all"
                :class="generationMode === 'chat' ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-gray-400'"
                @click="generationMode = 'chat'">
                <div class="flex items-center mb-2">
                  <input type="radio" v-model="generationMode" value="chat" class="mr-2">
                  <h4 class="font-medium text-gray-900">对话生成模式</h4>
                </div>
                <p class="text-sm text-gray-600">通过多轮对话逐步完善教案内容</p>
                <div class="mt-2 text-xs text-gray-500">
                  <i class="fas fa-comments mr-1"></i>交互式、可调整、适合个性化需求
                </div>
              </div>
            </div>
          </div>

          <!-- 一键生成模式 -->
          <div v-if="generationMode === 'oneshot'" class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- LLM配置 -->
            <div class="border rounded-lg p-4">
              <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900">AI模型配置</h3>
                <button @click="goToModelConfig"
                  class="px-3 py-1 text-sm bg-blue-100 text-blue-600 rounded-md hover:bg-blue-200 transition-colors">
                  <i class="fas fa-cog mr-1"></i>
                  模型配置
                </button>
              </div>
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">选择AI模型</label>
                  <select v-model="selectedLLM"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">请选择模型</option>
                    <option v-for="model in modelConfigStore.availableModels" :key="model.id" :value="model.id">
                      {{ model.name }}
                    </option>
                  </select>
                  <p v-if="modelConfigStore.availableModels.length === 0" class="text-sm text-gray-500 mt-1">
                    暂无可用模型，请先在模型配置中设置API密钥
                  </p>
                </div>

                <div v-if="selectedLLM">
                  <label class="block text-sm font-medium text-gray-700 mb-2">API密钥状态</label>
                  <div class="flex items-center space-x-2">
                    <span v-if="modelConfigStore.getModelConfig(selectedLLM)?.apiKey"
                      class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                      <i class="fas fa-check-circle mr-1"></i>
                      已配置
                    </span>
                    <span v-else
                      class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                      <i class="fas fa-exclamation-circle mr-1"></i>
                      未配置
                    </span>
                  </div>
                </div>

                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">生成提示词</label>
                  <textarea v-model="customPrompt" rows="4"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="可选：自定义生成提示词"></textarea>
                  
                  <!-- 提示词预览 -->
                  <div class="mt-2">
                    <button @click="showPromptPreview = !showPromptPreview" 
                      class="text-sm text-blue-600 hover:text-blue-800">
                      <i class="fas" :class="showPromptPreview ? 'fa-eye-slash' : 'fa-eye'"></i>
                      {{ showPromptPreview ? '隐藏' : '预览' }}提示词内容
                    </button>
                    
                    <div v-if="showPromptPreview" class="mt-2 p-3 bg-gray-50 rounded-md border max-h-60 overflow-y-auto">
                      <h4 class="text-sm font-medium text-gray-700 mb-2">处理后的提示词预览：</h4>
                      <pre class="text-sm text-gray-800 whitespace-pre-wrap">{{ getProcessedPromptPreview() }}</pre>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 生成控制 -->
            <div class="border rounded-lg p-4">
              <h3 class="text-lg font-medium text-gray-900 mb-4">生成控制</h3>
              <div class="space-y-4">
                <button @click="generateLessonPlan"
                  :disabled="!selectedLLM || !modelConfigStore.getModelConfig(selectedLLM)?.apiKey || isGenerating"
                  class="w-full px-4 py-3 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:bg-gray-400">
                  <i class="fas fa-magic mr-2" :class="{ 'fa-spin': isGenerating }"></i>
                  {{ isGenerating ? 'AI生成中...' : '开始生成教案' }}
                </button>

                <!-- 生成进度 -->
                <div v-if="isGenerating" class="w-full bg-gray-200 rounded-full h-2">
                  <div class="bg-green-600 h-2 rounded-full transition-all duration-300"
                    :style="{ width: generationProgress + '%' }"></div>
                </div>
              </div>
            </div>
          </div>

          <!-- 导航按钮 -->
          <div class="flex justify-between">
            <button @click="prevStep" class="px-6 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700">
              上一步
            </button>
            <button @click="nextStep" :disabled="!generatedContent"
              class="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400">
              下一步
            </button>
          </div>
        </div>

        <!-- 步骤4: 预览和导出 -->
        <div v-if="currentStep === 4" class="space-y-6">
          <h2 class="text-xl font-semibold text-gray-900">步骤4: 预览和导出</h2>

          <!-- 生成的教案预览 -->
          <div class="border rounded-lg p-4">
            <div class="flex justify-between items-center mb-4">
              <h3 class="text-lg font-medium text-gray-900">生成的教案</h3>
              <div class="space-x-2">
                <button @click="editContent = !editContent"
                  class="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700">
                  {{ editContent ? '预览模式' : '编辑模式' }}
                </button>
              </div>
            </div>

            <!-- 编辑模式 -->
            <div v-if="editContent" class="space-y-4">
              <textarea v-model="generatedContent" rows="20"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm"
                placeholder="生成的教案内容将显示在这里..."></textarea>
            </div>

            <!-- 预览模式 -->
            <div v-else class="bg-gray-50 rounded-md p-4 max-h-96 overflow-y-auto">
              <div v-if="generatedContent" class="prose max-w-none" v-html="renderedContent"></div>
              <div v-else class="text-gray-500 text-center py-8">暂无生成内容</div>
            </div>
          </div>

          <!-- 导出选项 -->
          <div class="border rounded-lg p-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">导出选项</h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <button @click="saveAsMd" :disabled="!generatedContent"
                class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400">
                <i class="fas fa-download mr-2"></i>
                保存为MD
              </button>
              <button @click="convertToDoc" :disabled="!generatedContent || isConverting"
                class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:bg-gray-400">
                <i class="fas fa-file-word mr-2" :class="{ 'fa-spin': isConverting }"></i>
                {{ isConverting ? '转换中...' : '转换为DOC' }}
              </button>
              <button @click="resetGenerator" class="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700">
                <i class="fas fa-redo mr-2"></i>
                重新开始
              </button>
            </div>
          </div>

          <!-- 导航按钮 -->
          <div class="flex justify-between">
            <button @click="prevStep" class="px-6 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700">
              上一步
            </button>
            <button @click="resetGenerator" class="px-6 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
              完成
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { marked } from 'marked'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import { useModelConfigStore } from '@/stores/modelConfig'
import LessonPlanService from '@/services/lessonPlanService'
import { ElMessage, ElNotification } from 'element-plus'

// 类型定义
interface LLMConfig {
  model: string
  apiKey?: string
  baseUrl?: string
  provider?: string
  temperature?: number
  maxTokens?: number
}

interface FileInfo {
  name: string
  path: string
  size: number
  lastModified: string
}

// 认证状态
const authStore = useAuthStore()
const router = useRouter()
const modelConfigStore = useModelConfigStore()

// 步骤定义
const steps = ['文档转换', '选择文件', 'AI生成', '预览导出']
const currentStep = ref(1)

// 步骤1: 文档转换
const selectedDocFile = ref<File | null>(null)
const isConverting = ref(false)
const conversionResults = ref<Array<{ file: string, success: boolean, error?: string }>>([])
const docFiles = ref<FileInfo[]>([])

// PPTX转换相关
const selectedPptxFile = ref<File | null>(null)
const isPptxConverting = ref(false)
const pptxConversionResults = ref<Array<{ file: string, success: boolean, error?: string }>>([])
const pptxOutputName = ref('')
const pptxImageDir = ref('')
const pptxDisableImage = ref(false)
const pptxEnableSlides = ref(false)

// 步骤2: 文件选择
const selectedMdFiles = ref<Array<{ name: string, content: string, file: File }>>([]) // 支持多个MD文件
const selectedMdContent = ref('') // 保留用于向后兼容
const expandedPreviews = ref<number[]>([]) // 展开预览的文件索引
const selectedTemplate = ref('')
const templateContent = ref('')
const mdFiles = ref<FileInfo[]>([])
const mdContent = ref('')
const outputDirectory = ref('d:\\WebProjects\\qdkj-course\\chapter03-05\\generated')
const docDirectory = ref('d:\\WebProjects\\qdkj-course\\chapter03-05\\generated')

// 步骤3: LLM配置
const selectedLLM = ref('')
const customPrompt = ref(`请你以 {ppt.md} 为线索，以 {handout.md} 为材料，结合你对Vue模板指令的理解和经验，
以 {template.md} 为输出格式，写一个2*2学时2*90分钟的教案，1学时45分钟一个输出文件。
要求：
1、整个4个学时以待办事项案例贯穿，待办事项的截图参见附图所示。
2、第1学时，主题是模板指令概述、模板插值、表单数据绑定
3、第2学时，主题是事件绑定
4、第3学时，主题是结构渲染，模板指令v-if、v-else、v-for、v-show
5、第4学时，主题是属性和样式绑定，包括一般属性绑定、style样式绑定和class属性绑定
请你在设计中体现OBE和BOPPPS的理念和教学模式。
注意：请把实例代码写在 表格外面，不要在表格里面写代码。`)
const isGenerating = ref(false)
const generationProgress = ref(0)
const llmModels = ref<LLMConfig[]>([])

// 步骤4: 预览和导出
const generatedContent = ref('')
const editContent = ref(false)

// 生成模式
const generationMode = ref('oneshot') // 'oneshot' | 'chat'

// 提示词预览
const showPromptPreview = ref(false)

// 对话模式相关
const chatMessages = ref<Array<{
  role: 'user' | 'assistant'
  content: string
  timestamp: number
  files?: Array<{ name: string, content: string, type: string }>
}>>([])  
const chatInput = ref('')
const selectedChatFiles = ref<File[]>([])
const isChatGenerating = ref(false)
const chatContainer = ref<HTMLElement | null>(null)
const chatFileInput = ref<HTMLInputElement | null>(null)

// 计算属性
const renderedContent = computed(() => {
  if (!generatedContent.value) return ''
  return marked(generatedContent.value)
})

// 步骤导航
const nextStep = () => {
  if (currentStep.value < steps.length) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--
  }
}

const goToStep = (step: number) => {
  if (step >= 1 && step <= steps.length) {
    currentStep.value = step
  }
}

// 文件选择功能
const handleDocFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    selectedDocFile.value = file
  }
}

// 文档转换功能
const convertDocToMd = async () => {
  if (!selectedDocFile.value) {
    alert('请先选择DOC文件')
    return
  }

  isConverting.value = true
  conversionResults.value = []

  try {
    // 创建临时文件路径
    const tempDir = 'd:\\WebProjects\\qdkj-course\\chapter03-05\\generated'
    const fileName = selectedDocFile.value.name
    const nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'))
    const inputPath = `${tempDir}\\${fileName}`
    const outputPath = `${tempDir}\\handout.md`

    // 首先需要将文件保存到服务器
    const formData = new FormData()
    formData.append('file', selectedDocFile.value)
    formData.append('targetPath', inputPath)

    // 上传文件到服务器
    const uploadResponse = await fetch('/api/lesson-plan/upload', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      },
      body: formData
    })

    if (!uploadResponse.ok) {
      throw new Error('文件上传失败')
    }

    // 执行转换
    await LessonPlanService.convertDocToMd({
      inputPath,
      outputPath
    })

    conversionResults.value.push({
      file: fileName,
      success: true
    })

    // 转换完成后刷新文件列表
    await loadMdFiles()

  } catch (error) {
    console.error('转换过程中出错:', error)
    conversionResults.value.push({
      file: selectedDocFile.value?.name || '未知文件',
      success: false,
      error: error instanceof Error ? error.message : '转换失败'
    })
  } finally {
    isConverting.value = false
  }
}

// PPTX文件选择功能
const handlePptxFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    selectedPptxFile.value = file
  }
}

// PPTX转换功能
const convertPptxToMd = async () => {
  if (!selectedPptxFile.value) {
    alert('请先选择PPTX文件')
    return
  }

  isPptxConverting.value = true
  pptxConversionResults.value = []

  try {
    // 创建临时文件路径
    const tempDir = 'd:\\WebProjects\\qdkj-course\\chapter03-05\\generated'
    const fileName = selectedPptxFile.value.name
    const nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'))
    const inputPath = `${tempDir}\\${fileName}`
    
    // 设置输出文件名和图片目录
    const outputFileName = pptxOutputName.value || 'ppt.md'
    const imageDir = pptxImageDir.value || 'img'
    const outputPath = `${tempDir}\\${outputFileName}`
    const imagePath = `${tempDir}\\${imageDir}`

    // 首先需要将文件保存到服务器
    const formData = new FormData()
    formData.append('file', selectedPptxFile.value)
    formData.append('targetPath', inputPath)

    // 上传文件到服务器
    const uploadResponse = await fetch('/api/lesson-plan/upload', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      },
      body: formData
    })

    if (!uploadResponse.ok) {
      throw new Error('文件上传失败')
    }

    // 构建pptx2md命令参数
    const pptxArgs = {
      inputPath,
      outputPath,
      imageDir: imagePath,
      disableImage: pptxDisableImage.value,
      enableSlides: pptxEnableSlides.value
    }

    // 执行PPTX转换
    await LessonPlanService.convertPptxToMd(pptxArgs)

    pptxConversionResults.value.push({
      file: fileName,
      success: true
    })

    // 转换完成后刷新文件列表
    await loadMdFiles()

  } catch (error) {
    console.error('PPTX转换过程中出错:', error)
    pptxConversionResults.value.push({
      file: selectedPptxFile.value?.name || '未知文件',
      success: false,
      error: error instanceof Error ? error.message : 'PPTX转换失败'
    })
  } finally {
    isPptxConverting.value = false
  }
}

// 文件选择功能
const handleMdFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files

  if (files && files.length > 0) {
    try {
      // 清空之前选择的文件
      selectedMdFiles.value = []
      
      // 处理所有选择的文件
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        const content = await file.text()
        selectedMdFiles.value.push({
          name: file.name,
          content: content,
          file: file
        })
      }
      
      // 为了向后兼容，将第一个文件的内容设置为selectedMdContent
      if (selectedMdFiles.value.length > 0) {
        selectedMdContent.value = selectedMdFiles.value[0].content
      }
    } catch (error) {
      console.error('读取文件失败:', error)
      alert('读取文件失败: ' + (error instanceof Error ? error.message : '未知错误'))
    }
  }
}

// 移除选中的MD文件
const removeMdFile = (index: number) => {
  selectedMdFiles.value.splice(index, 1)
  // 移除对应的预览展开状态
  expandedPreviews.value = expandedPreviews.value.filter(i => i !== index).map(i => i > index ? i - 1 : i)
  
  // 更新向后兼容的selectedMdContent
  if (selectedMdFiles.value.length > 0) {
    selectedMdContent.value = selectedMdFiles.value[0].content
  } else {
    selectedMdContent.value = ''
  }
}

// 切换文件预览展开状态
const toggleFilePreview = (index: number) => {
  const expandedIndex = expandedPreviews.value.indexOf(index)
  if (expandedIndex > -1) {
    expandedPreviews.value.splice(expandedIndex, 1)
  } else {
    expandedPreviews.value.push(index)
  }
}

// 加载文件列表
const loadDocFiles = async () => {
  try {
    // 获取文件列表并手动添加lastModified字段
    const files = await LessonPlanService.getDocFiles(docDirectory.value);
    docFiles.value = files.map(file => ({
      ...file,
      lastModified: new Date().toISOString() // 由于API返回的数据没有lastModified字段,这里添加当前时间作为默认值
    }));
  } catch (error) {
    console.error('加载DOC文件列表失败:', error)
  }
}

const loadMdFiles = async () => {
  try {
    // 获取文件列表并手动添加lastModified字段
    const files = await LessonPlanService.getMdFiles(docDirectory.value);
    mdFiles.value = files.map(file => ({
      ...file,
      lastModified: new Date().toISOString() // 由于API返回的数据没有lastModified字段,这里添加当前时间作为默认值
    }));
  } catch (error) {
    console.error('加载MD文件列表失败:', error)
  }
}

// 加载模板内容
const loadTemplate = async () => {
  // 只有在用户已登录时才加载模板
  if (!authStore.token) {
    console.log('用户未登录，跳过模板加载')
    return
  }
  
  if (selectedTemplate.value === 'default') {
    try {
      templateContent.value = await LessonPlanService.getTemplate('default')
    } catch (error) {
      console.error('加载模板失败:', error)
    }
  }
}

// 加载LLM模型列表
const loadLLMModels = async () => {
  try {
    llmModels.value = await LessonPlanService.getLLMModels()
  } catch (error) {
    console.error('加载LLM模型列表失败:', error)
  }
}

// 监听模板选择变化
const watchTemplate = () => {
  if (selectedTemplate.value) {
    loadTemplate()
  }
}

// 跳转到模型配置页面
const goToModelConfig = () => {
  router.push('/model-config')
}

// 获取处理后的提示词预览
const getProcessedPromptPreview = () => {
  let processedPrompt = customPrompt.value
  
  // 查找并替换 {ppt.md}
  const pptFile = selectedMdFiles.value.find(file => file.name.toLowerCase().includes('ppt'))
  if (pptFile) {
    processedPrompt = processedPrompt.replace(/{ppt\.md}/g, `以下是PPT内容：\n${pptFile.content.substring(0, 200)}${pptFile.content.length > 200 ? '...(内容已截断)' : ''}`)
  } else {
    processedPrompt = processedPrompt.replace(/{ppt\.md}/g, '未选择PPT文件')
  }
  
  // 查找并替换 {handout.md}
  const handoutFile = selectedMdFiles.value.find(file => file.name.toLowerCase().includes('handout'))
  if (handoutFile) {
    processedPrompt = processedPrompt.replace(/{handout\.md}/g, `以下是讲义内容：\n${handoutFile.content.substring(0, 200)}${handoutFile.content.length > 200 ? '...(内容已截断)' : ''}`)
  } else {
    processedPrompt = processedPrompt.replace(/{handout\.md}/g, '未选择讲义文件')
  }
  
  // 替换 {template.md}
  if (templateContent.value) {
    processedPrompt = processedPrompt.replace(/{template\.md}/g, `以下是模板格式：\n${templateContent.value.substring(0, 200)}${templateContent.value.length > 200 ? '...(内容已截断)' : ''}`)
  } else {
    processedPrompt = processedPrompt.replace(/{template\.md}/g, '未选择模板')
  }
  
  return processedPrompt
}

// AI生成教案
const generateLessonPlan = async () => {
  // 检查上一步是否选择了必要的文件和模板
  const missingItems = []
  
  if (selectedMdFiles.value.length === 0) {
    missingItems.push('MD文件')
  }
  
  if (!templateContent.value) {
    missingItems.push('教案模板')
  }
  
  if (!selectedLLM.value) {
    missingItems.push('AI模型')
  }
  
  if (missingItems.length > 0) {
    const message = `请先完成以下选择，然后返回上一步：\n\n缺少项目：\n${missingItems.map(item => `• ${item}`).join('\n')}\n\n当前状态：\n• MD文件: ${selectedMdFiles.value.length > 0 ? `已选择${selectedMdFiles.value.length}个文件` : '未选择'}\n• 模板: ${templateContent.value ? '已选择' : '未选择'}\n• AI模型: ${selectedLLM.value || '未选择'}`
    
    if (confirm(message + '\n\n点击确定返回上一步进行选择')) {
      prevStep()
    }
    return
  }

  // 获取选中模型的配置
  // 通过模型ID查找配置
  const modelConfig = modelConfigStore.getModelConfig(selectedLLM.value)
  if (!modelConfig || !modelConfig.apiKey) {
    alert('请先在模型配置中设置该模型的API密钥')
    return
  }

  isGenerating.value = true
  generationProgress.value = 0

  // 模拟进度
  const progressInterval = setInterval(() => {
    if (generationProgress.value < 90) {
      generationProgress.value += Math.random() * 10
    }
  }, 500)

  try {
    const llmConfig: LLMConfig = {
      model: modelConfig.model,
      apiKey: modelConfig.apiKey,
      baseUrl: modelConfig.baseUrl || modelConfig.apiUrl,
      provider: modelConfig.provider,
      temperature: 0.7,
      maxTokens: 2000
    }
    // 验证必要字段
    if (!llmConfig.model) {
      throw new Error('模型名称不能为空')
    }
    if (!llmConfig.apiKey) {
      throw new Error('API密钥不能为空')
    }
    // 合并所有选中的markdown文件内容
    const combinedMdContent = selectedMdFiles.value.map((file, index) => {
      return `## 文件${index + 1}: ${file.name}\n\n${file.content}`
    }).join('\n\n---\n\n')
    
    // 处理提示词中的占位符，替换为实际文件内容
    let processedPrompt = customPrompt.value
    
    // 查找并替换 {ppt.md}
    const pptFile = selectedMdFiles.value.find(file => file.name.toLowerCase().includes('ppt'))
    if (pptFile) {
      processedPrompt = processedPrompt.replace(/{ppt\.md}/g, `以下是PPT内容：\n${pptFile.content}`)
    } else {
      processedPrompt = processedPrompt.replace(/{ppt\.md}/g, '未选择PPT文件')
    }
    
    // 查找并替换 {handout.md}
    const handoutFile = selectedMdFiles.value.find(file => file.name.toLowerCase().includes('handout'))
    if (handoutFile) {
      processedPrompt = processedPrompt.replace(/{handout\.md}/g, `以下是讲义内容：\n${handoutFile.content}`)
    } else {
      processedPrompt = processedPrompt.replace(/{handout\.md}/g, '未选择讲义文件')
    }
    
    // 替换 {template.md}
    processedPrompt = processedPrompt.replace(/{template\.md}/g, `以下是模板格式：\n${templateContent.value}`)
    
    const result = await LessonPlanService.generateLessonPlanWithAI({
      mdContent: combinedMdContent,
      templateContent: templateContent.value,
      llmConfig,
      prompt: processedPrompt
    })
    generatedContent.value = result.content || ''
    generationProgress.value = 100
  } catch (error) {

    alert('生成教案失败: ' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    clearInterval(progressInterval)
    isGenerating.value = false
  }
}

// 保存为MD文件
const saveAsMd = () => {
  if (!generatedContent.value) return

  const blob = new Blob([generatedContent.value], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `教案_${new Date().toISOString().slice(0, 10)}.md`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 转换为DOC文件
const convertToDoc = async () => {
  if (!generatedContent.value) return

  if (!outputDirectory.value) {
    alert('请先选择输出目录')
    return
  }

  isConverting.value = true

  try {
    // 生成输出文件路径
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
    const outputPath = `${outputDirectory.value}\\lesson-plan-${timestamp}.docx`

    // 先保存为临时MD文件
    const tempMdPath = `${outputDirectory.value}\\temp-lesson-plan.md`
    await LessonPlanService.writeFile({
      filePath: tempMdPath,
      content: generatedContent.value
    })

    // 转换为Word文档
    await LessonPlanService.convertMdToDoc({
      inputPath: tempMdPath,
      outputPath
    })

    alert('导出成功！文件保存在: ' + outputPath)
  } catch (error) {
    console.error('转换过程中出错:', error)
    alert('导出失败: ' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    isConverting.value = false
  }
}

// 重置生成器
const resetGenerator = () => {
  currentStep.value = 1
  selectedDocFile.value = null
  selectedMdFiles.value = [] // 重置多文件选择
  selectedMdContent.value = ''
  expandedPreviews.value = [] // 重置预览展开状态
  selectedTemplate.value = ''
  templateContent.value = ''
  selectedLLM.value = ''
  customPrompt.value = ''
  generatedContent.value = ''
  editContent.value = false
  conversionResults.value = []
  isConverting.value = false
  isGenerating.value = false
  generationProgress.value = 0
  // 重置对话模式
  generationMode.value = 'oneshot'
  chatMessages.value = []
  chatInput.value = ''
  selectedChatFiles.value = []
  isChatGenerating.value = false
}

// 对话模式相关方法
const handleChatFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = Array.from(target.files || [])
  
  for (const file of files) {
    if (file.size > 10 * 1024 * 1024) { // 10MB限制
      alert(`文件 ${file.name} 过大，请选择小于10MB的文件`)
      continue
    }
    selectedChatFiles.value.push(file)
  }
  
  // 清空input
  target.value = ''
}

const removeChatFile = (index: number) => {
  selectedChatFiles.value.splice(index, 1)
}

const addQuickPrompt = (prompt: string) => {
  chatInput.value = prompt
}

const clearChat = () => {
  if (confirm('确定要清空所有对话记录吗？')) {
    chatMessages.value = []
    generatedContent.value = ''
    // 清空本地存储的对话历史
    localStorage.removeItem('lessonPlan_chatHistory')
  }
}

// 保存对话历史到本地存储
const saveChatHistory = () => {
  const chatData = {
    messages: chatMessages.value,
    generatedContent: generatedContent.value,
    timestamp: Date.now(),
    mdFiles: selectedMdFiles.value.map(file => ({ name: file.name, content: file.content })),
    template: selectedTemplate.value
  }
  localStorage.setItem('lessonPlan_chatHistory', JSON.stringify(chatData))
}

// 从本地存储恢复对话历史
const loadChatHistory = () => {
  try {
    const savedData = localStorage.getItem('lessonPlan_chatHistory')
    if (savedData) {
      const chatData = JSON.parse(savedData)
      if (chatData.messages && Array.isArray(chatData.messages)) {
        chatMessages.value = chatData.messages
        if (chatData.generatedContent) {
          generatedContent.value = chatData.generatedContent
        }
        // 恢复多文件信息（新格式）
        if (chatData.mdFiles && Array.isArray(chatData.mdFiles)) {
          selectedMdFiles.value = chatData.mdFiles.map((file: { name: string; content: string }) => ({
            name: file.name,
            content: file.content,
            file: null // 历史记录中没有原始File对象
          }))
          // 更新向后兼容的selectedMdContent
          if (selectedMdFiles.value.length > 0) {
            selectedMdContent.value = selectedMdFiles.value[0].content
          }
        }
        // 向后兼容旧格式
        else if (chatData.mdContent) {
          selectedMdContent.value = chatData.mdContent
          selectedMdFiles.value = [{
            name: '历史文档.md',
            content: chatData.mdContent,
            file: {} as File
          }]
        }
        return true
      }
    }
  } catch (error) {
    console.error('加载对话历史失败:', error)
  }
  return false
}

// 导出对话记录
const exportChatHistory = () => {
  if (chatMessages.value.length === 0) {
    alert('没有对话记录可以导出')
    return
  }
  
  const chatData = {
    title: '教案生成对话记录',
    exportTime: new Date().toLocaleString('zh-CN'),
    messages: chatMessages.value,
    generatedContent: generatedContent.value
  }
  
  const dataStr = JSON.stringify(chatData, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  
  const link = document.createElement('a')
  link.href = URL.createObjectURL(dataBlob)
  link.download = `教案对话记录_${new Date().toISOString().slice(0, 10)}.json`
  link.click()
  
  URL.revokeObjectURL(link.href)
}

// 导入对话记录
const importChatHistory = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const result = e.target?.result as string
      const chatData = JSON.parse(result)
      
      if (chatData.messages && Array.isArray(chatData.messages)) {
        if (confirm('导入对话记录将覆盖当前对话，确定要继续吗？')) {
          chatMessages.value = chatData.messages
          if (chatData.generatedContent) {
            generatedContent.value = chatData.generatedContent
          }
          saveChatHistory() // 保存到本地存储
          scrollToBottom()
        }
      } else {
        alert('文件格式不正确')
      }
    } catch (error) {
      console.error('导入对话记录失败:', error)
      alert('导入失败，请检查文件格式')
    }
  }
  
  reader.readAsText(file)
  target.value = '' // 清空input
}

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const scrollToBottom = () => {
  if (chatContainer.value) {
    setTimeout(() => {
      chatContainer.value!.scrollTop = chatContainer.value!.scrollHeight
    }, 100)
  }
}

const sendChatMessage = async () => {
  if (!chatInput.value.trim() && selectedChatFiles.value.length === 0) return
  if (!selectedLLM.value) {
    alert('请先选择AI模型')
    return
  }
  
  const modelConfig = modelConfigStore.getModelConfig(selectedLLM.value)
  if (!modelConfig || !modelConfig.apiKey) {
    alert('请先在模型配置中设置该模型的API密钥')
    return
  }

  // 处理文件内容
  const files: Array<{ name: string, content: string, type: string }> = []
  for (const file of selectedChatFiles.value) {
    try {
      const content = await file.text()
      files.push({
        name: file.name,
        content,
        type: file.type || 'text/plain'
      })
    } catch (error) {
      console.error(`读取文件 ${file.name} 失败:`, error)
    }
  }

  // 添加用户消息
  const userMessage = {
    role: 'user' as const,
    content: chatInput.value.trim(),
    timestamp: Date.now(),
    files: files.length > 0 ? files : undefined
  }
  
  chatMessages.value.push(userMessage)
  
  // 清空输入
  const currentInput = chatInput.value
  chatInput.value = ''
  selectedChatFiles.value = []
  
  // 滚动到底部
  scrollToBottom()
  
  // 开始生成回复
  isChatGenerating.value = true
  
  try {
    // 构建上下文消息
    const contextMessages = chatMessages.value.map(msg => {
      let content = msg.content
      if (msg.files && msg.files.length > 0) {
        const fileContents = msg.files.map(f => `\n\n文件: ${f.name}\n内容:\n${f.content}`).join('')
        content += fileContents
      }
      return {
        role: msg.role,
        content
      }
    })
    
    // 添加系统提示
    const systemPrompt = `你是一个专业的教案生成助手。用户正在使用教案生成器，已经选择了以下内容：
${selectedMdFiles.value.length > 0 ? `\n参考文档内容（共${selectedMdFiles.value.length}个文件）：\n${selectedMdFiles.value.map((file, index) => `文件${index + 1}: ${file.name}\n${file.content.substring(0, 500)}...`).join('\n\n')}` : ''}
${templateContent.value ? `\n教案模板：\n${templateContent.value.substring(0, 500)}...` : ''}

请根据用户的要求，帮助他们生成和完善教案。你可以：
1. 分析文档内容
2. 根据模板生成教案
3. 完善教案的各个部分
4. 回答相关问题
5. 提供建议和改进意见

请用中文回复，内容要专业、详细、实用。`
    
    const messages = [
      { role: 'system', content: systemPrompt },
      ...contextMessages
    ]

    const llmConfig = {
      model: modelConfig.model,
      apiKey: modelConfig.apiKey,
      baseUrl: modelConfig.baseUrl || modelConfig.apiUrl,
      provider: modelConfig.provider,
      temperature: 0.7,
      maxTokens: 4000
    }

    // 调用AI API
    const response = await LessonPlanService.chatWithAI({
      messages: messages as Array<{ role: 'user' | 'assistant' | 'system'; content: string }>,
      llmConfig
    })
    
    // 添加AI回复
    const aiMessage = {
      role: 'assistant' as const,
      content: response?.content || '抱歉，我无法生成回复。',
      timestamp: Date.now()
    }
    
    chatMessages.value.push(aiMessage)
    
    // 如果AI回复包含完整的教案内容，更新生成内容
    if (response?.content && response.content.length > 500) {
      generatedContent.value = response.content
    }
    
    // 保存对话历史
    saveChatHistory()
    
  } catch (error) {
    console.error('发送消息失败:', error)
    
    // 添加错误消息
    const errorMessage = {
      role: 'assistant' as const,
      content: `抱歉，发生了错误：${error instanceof Error ? error.message : '未知错误'}`,
      timestamp: Date.now()
    }
    
    chatMessages.value.push(errorMessage)
  } finally {
    isChatGenerating.value = false
    scrollToBottom()
  }
}

// 组件挂载时的初始化
onMounted(async () => {
  try {
    // 只有在用户已登录时才加载需要认证的资源
    if (authStore.token) {
      // 加载模型配置
      await modelConfigStore.loadConfigs()
      
      // 自动选择默认模型
      const defaultModel = modelConfigStore.defaultConfig
      if (defaultModel && defaultModel.id) {
        selectedLLM.value = defaultModel.id
      }
      
      // 加载LLM模型列表
      llmModels.value = await LessonPlanService.getLLMModels()
      
      // 加载模板内容
      templateContent.value = await LessonPlanService.getTemplate('Template.md')
      
      // 如果有默认目录，加载文件列表
      if (outputDirectory.value) {
        const files = await LessonPlanService.getMdFiles(outputDirectory.value);
        mdFiles.value = files.map(file => ({
          ...file,
          lastModified: new Date().toISOString() // 添加缺失的lastModified字段
        }));
      }
    }

    // 自动加载对话历史（不需要认证）
    if (loadChatHistory()) {
      console.log('对话历史已自动恢复')
    }
  } catch (error) {
    console.error('初始化失败:', error)
  }
})
</script>

<style scoped>
.prose {
  max-width: none;
}

.prose h1 {
  @apply text-2xl font-bold text-gray-900 mb-4;
}

.prose h2 {
  @apply text-xl font-semibold text-gray-800 mb-3;
}

.prose h3 {
  @apply text-lg font-medium text-gray-700 mb-2;
}

.prose p {
  @apply text-gray-600 mb-3;
}

.prose ul,
.prose ol {
  @apply text-gray-600 mb-3 pl-6;
}

.prose li {
  @apply mb-1;
}

.prose table {
  @apply w-full border-collapse border border-gray-300 mb-4;
}

.prose th,
.prose td {
  @apply border border-gray-300 px-3 py-2 text-left;
}

.prose th {
  @apply bg-gray-50 font-medium;
}
</style>